package cors_middleware

import (
	"strings"

	"github.com/gin-gonic/gin"
)

type CORSConfig struct {
	AllowOrigins []string
	AllowMethods []string
	AllowHeaders []string
}

var DefaultCORSConfig = CORSConfig{
	AllowOrigins: []string{"*"},
	AllowMethods: []string{"GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"},
	AllowHeaders: []string{"Origin", "Content-Type", "Accept", "Authorization"},
}

func CORS() gin.HandlerFunc {
	return func(c *gin.Context) {
		if len(DefaultCORSConfig.AllowOrigins) > 0 {
			c.Writer.Header().Set("Access-Control-Allow-Origin", DefaultCORSConfig.AllowOrigins[0])
		} else {
			c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
		}
		if len(DefaultCORSConfig.AllowMethods) > 0 {
			c.Writer.Header().Set("Access-Control-Allow-Methods", strings.Join(DefaultCORSConfig.AllowMethods, ","))
		}
		if len(DefaultCORSConfig.AllowHeaders) > 0 {
			c.Writer.Header().Set("Access-Control-Allow-Headers", strings.Join(DefaultCORSConfig.AllowHeaders, ","))
		}

		if c.Request.Method == "OPTIONS" {
			c.AbortWithStatus(204)
			return
		}

		c.Next()
	}
}
